package com.zmn.uac.util;

import com.zmn.consts.GlobalConsts;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.HttpStatus;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 类描述：http请求工具类
 *
 * @author xujie
 * @since 2021/06/16 16:34
 */
@Slf4j
public class HttpClientsUtil {

    private static final String TAG = "http请求工具类";


    /**
     * 执行GET请求
     * @param url
     * @return
     */
    public static String executeGet(String url) {
        OkHttpClient okHttpClient = new OkHttpClient();
        String responseBody = GlobalConsts.SPLITER_EMPTY;
        Request request = new Request
                .Builder()
                .url(url)
                .build();
        try (Response response = okHttpClient.newCall(request).execute()) {
            if (response.code() == HttpStatus.SC_OK) {
                responseBody =  Objects.requireNonNull(response.body()).string();
            }
        } catch (Exception e) {
            log.error("[{}], 执行get请求异常, 返回信息：{}", TAG, ExceptionUtils.getStackTrace(e));
        }

        return responseBody;
    }


    /**
     * 执行POST请求
     * @param url
     * @return
     */
    public static String executePost(String url, Map<String, String> params) {
        OkHttpClient okHttpClient = new OkHttpClient();
        String responseBody = GlobalConsts.SPLITER_EMPTY;
        FormBody.Builder builder = new FormBody.Builder();
        if (params != null && params.keySet().size() > 0) {
            params.keySet().forEach(key-> builder.add(key, params.get(key)));
        }
        Request request = new Request
                .Builder()
                .url(url)
                .post(builder.build())
                .build();
        try (Response response = okHttpClient.newCall(request).execute()) {
            if (response.code() == HttpStatus.SC_OK) {
                responseBody = Objects.requireNonNull(response.body()).string();
            }
        } catch (Exception e) {
            log.error("[{}], 执行post请求异常, 返回信息：{}", TAG, ExceptionUtils.getStackTrace(e));
        }

        return responseBody;
    }

    /**
     * 拼接url参数
     *
     * @param treeMap treeMap
     * @return url
     * @author xujie
     * @since 2021/05/20
     */
    public static String splicingUrlData(TreeMap<String, String> treeMap) {
        StringBuilder sb = new StringBuilder();
        AtomicReference<String> str = new AtomicReference<>("?");
        treeMap.forEach((k, v) -> {
            sb.append(str.get());
            sb.append(k);
            sb.append("=");
            try {
                sb.append(URLEncoder.encode(v, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            str.set("&");
        });
        return sb.toString();
    }
}
